<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="1000px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-form-item label="工单Id" prop="workOrderId" v-show="false">
          <el-input v-model="formData.workOrderId" placeholder="请输入工单Id"/>
        </el-form-item>
        <el-form-item label="工单号" prop="workOrderNo">
          <el-select
            v-model="formData.workOrderNo"
            placeholder="请输入工单号进行搜索"
            filterable
            remote
            :remote-method="workOrderRemoteMethod"
            :loading="workOrderLoading"
            @change="handleWorkOrderChange"
            style="width: 100%"
          >
            <el-option
              v-for="workOrder in workOrderList"
              :key="workOrder.id"
              :label="workOrder.workOrderNo"
              :value="workOrder.workOrderNo"
            >
              <span style="float: left">{{ workOrder.workOrderNo }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ workOrder.materialName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="工序" prop="procedureId">
          <el-select
            v-model="formData.procedureId"
            placeholder="请选择工序"
            filterable
            remote
            style="width: 100%"
          >
            <el-option
              v-for="batch in batchList"
              :key="batch.id"
              :label="batch.procedureName"
              :value="batch.procedureId"
            >
              <span style="float: left">{{ batch.procedureName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ batch.procedureCode }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="额外物料" prop="otherMaterialList">
          <el-button type="primary" size="mini" @click="addMaterial" style="margin-bottom: 10px;">
            <i class="el-icon-plus"></i> 新增物料
          </el-button>
          <el-table :data="formData.otherMaterialList" style="width: 100%" border max-height="400px">
            <el-table-column label="序号" type="index" width="80" align="center"/>
            <el-table-column label="物料" align="center">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.materialId"
                  placeholder="请选择物料"
                  filterable
                  remote
                  :remote-method="(query) => materialRemoteMethod(query, scope.$index)"
                  :loading="scope.row.materialLoading"
                  style="width: 100%"
                  @change="handleMaterialSelect($event, scope.$index)"
                >
                  <el-option v-for="material in scope.row.materialList" :key="material.id" :label="material.materialName"
                             :value="material.id">
                    <span style="float: left">{{ material.materialName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ material.materialNo }}</span>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" align="center" width="130">
              <template slot-scope="scope">
                <el-input v-model="scope.row.quantity" placeholder="请输入数量" size="small" type="number" min="1" step="1" style="width: 100px"/>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button type="danger" size="mini" @click="removeMaterial(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ReworkOrderApi from '@/api/production/reworkorder';
import * as WorkOrderApi from '@/api/production/reportwork';
import * as MaterialApi from '@/api/basic/material';

export default {
  name: "ReworkOrderForm",
  components: {},
  data() {
    return {
      batchList:[],
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 工单列表
      workOrderList: [],
      // 工单加载状态
      workOrderLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        reworkOrderNo: undefined,
        batchNo: undefined,
        materialId: undefined,
        materialNo: undefined,
        materialName: undefined,
        procedureId: undefined,
        procedureCode: undefined,
        procedureName: undefined,
        workOrderId: undefined,
        workOrderNo: undefined,
        processRouteId: undefined,
        processRouteNodeId: undefined,
        otherMaterialList: [],
      },
      // 表单校验
      formRules: {},
    };
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 如果id存在，则为编辑
      if (id) {
        this.formLoading = true;
        try {
          const res = await ReworkOrderApi.getReworkOrder(id);
          this.formData = res.data;
          // 确保otherMaterialList是数组
          if (!Array.isArray(this.formData.otherMaterialList)) {
            this.formData.otherMaterialList = [];
          }
          // 为已有物料行初始化必要字段并加载各自的物料列表
          for (let i = 0; i < this.formData.otherMaterialList.length; i++) {
            const row = this.formData.otherMaterialList[i];
            if (!row.materialList) row.materialList = [];
            if (!row.hasOwnProperty('materialLoading')) row.materialLoading = false;
            if (!row.hasOwnProperty('quantity')) row.quantity = 0;
            // 为每一行加载独立的物料列表
            await this.getMaterialListByRow(i);
          }
          this.dialogTitle = "修改返工工单";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增返工工单";
        // 新增时添加一个默认的物料行
        await this.addMaterial();
      }
      // 页面加载时默认搜索20条工单
      this.workOrderRemoteMethod('');
    },

    /** 物料远程搜索方法 */
    async materialRemoteMethod(query, index) {
      const row = this.formData.otherMaterialList[index];
      if (!row) return;
      
      if (query) {
        row.materialLoading = true;
        try {
          const params = {
            pageNo: 1,
            pageSize: 100,
            materialName: query
          };
          const res = await MaterialApi.getMaterialPage(params);
          row.materialList = res.data.list || [];
        } catch (error) {
          console.error('获取物料列表失败:', error);
          row.materialList = [];
        } finally {
          row.materialLoading = false;
        }
      } else {
        // 如果查询条件为空，默认显示前100条
        await this.getMaterialListByRow(index);
      }
    },

    /** 获取指定行的物料列表方法，默认获取前100条 */
    async getMaterialListByRow(index) {
      const row = this.formData.otherMaterialList[index];
      if (!row) return;
      
      try {
        row.materialLoading = true;
        const params = {
          pageNo: 1,
          pageSize: 100
        };
        const res = await MaterialApi.getMaterialPage(params);
        row.materialList = res.data.list || [];
      } catch (error) {
        console.error('获取物料列表失败:', error);
        row.materialList = [];
      } finally {
        row.materialLoading = false;
      }
    },

    /** 物料选择后处理 */
    handleMaterialSelect(materialId, index) {
      const row = this.formData.otherMaterialList[index];
      if (!row || !row.materialList) return;
      
      const selectedMaterial = row.materialList.find(item => item.id === materialId);
      if (selectedMaterial) {
        row.materialNo = selectedMaterial.materialNo;
        row.materialName = selectedMaterial.materialName;
      }
    },

    /** 添加物料明细行 */
    async addMaterial() {
      const newMaterial = {
        materialId: undefined,
        materialNo: '',
        materialName: '',
        quantity: 0,
        materialList: [],
        materialLoading: false
      };
      this.formData.otherMaterialList.push(newMaterial);
      
      // 为新添加的行初始化物料列表
      const index = this.formData.otherMaterialList.length - 1;
      await this.getMaterialListByRow(index);
    },

    /** 删除物料明细行 */
    removeMaterial(index) {
      this.formData.otherMaterialList.splice(index, 1);
    },




    /** 工单远程搜索方法 */
    async workOrderRemoteMethod(query) {
      this.workOrderLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 20,
          workOrderNo: query,
        };
        const response = await WorkOrderApi.getReportWorkPage(params);
        this.workOrderList = response.data.list || [];
      } catch (error) {
        console.error('搜索工单失败', error);
        this.workOrderList = [];
      } finally {
        this.workOrderLoading = false;
      }
    },

    /** 处理工单选择变化 */
    async handleWorkOrderChange(workOrderNo) {
      if (!workOrderNo) {
        return;
      }

      // 根据工单号查找对应的工单信息
      const selectedWorkOrder = this.workOrderList.find(item => item.workOrderNo === workOrderNo);
      if (selectedWorkOrder) {
        // 自动填充相关字段
        this.formData.workOrderId = selectedWorkOrder.workOrderId;
        this.formData.materialId = selectedWorkOrder.materialId;
        this.formData.batchNo = selectedWorkOrder.batchNo;

        // 获取批次号信息
        if (selectedWorkOrder.batchNo) {
          try {
              const res = await ReworkOrderApi.getByBatchNo(selectedWorkOrder.batchNo);
              this.batchList = res.data || [];
            // 可以根据返回的数据做相应处理
          } catch (error) {
            console.error('获取批次号信息失败:', error);
          }
        }
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ReworkOrderApi.updateReworkOrder(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await ReworkOrderApi.createReworkOrder(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        reworkOrderNo: undefined,
        batchNo: undefined,
        materialId: undefined,
        materialNo: undefined,
        materialName: undefined,
        procedureId: undefined,
        procedureCode: undefined,
        procedureName: undefined,
        workOrderId: undefined,
        workOrderNo: undefined,
        processRouteId: undefined,
        processRouteNodeId: undefined,
        otherMaterialList: [],
      };
      this.resetForm("formRef");
    }
  }
};
</script>
